import React,{useState,ChangeEvent} from 'react';
import useInput from '../../hooks/useInput';

interface ItemOption{
    text:string
}

let initOptions = function(count:number):ItemOption[]{ //[{text:''}]

    let arr:ItemOption[] = [];
    for(let i = 0;i<count;i++){
        arr.push({
            text:''
        })
    }
   return arr
}

const Create:React.FC = function(){
    
    let title = useInput('');

    let subTitle = useInput('');

   let [options,setOptions] = useState(initOptions(2));  //[{text:''},{text:''}]

    console.log("---options",options)

    let change = (index:number,e:ChangeEvent) => {
        // index e.target.value
        options[index].text = (e.target as HTMLInputElement).value;
        setOptions([...options])
    }

    //添加选项
    let addOptions = () =>{
        options.push({
            text:''
        })
        setOptions([...options])
    }

    //删除选项
    let disOptions = (index:number) => {
        if(options.length <= 2){
            return;
        }
        options.splice(index,1);
        setOptions([...options])
    }   

    return <div>
        <div>
            标题：<input type="text" placeholder="请输入标题" {...title}/>
        </div>
        <div>
            补充标题: <input type="text" placeholder="请输入补充标题" {...subTitle}/>
        </div>
        <div>
            <ul>
                {
                    options.map((item,index) => <li key={index}>
                        <span onClick={disOptions.bind(null,index)}>-</span>
                        <input type="text" placeholder="选项" value={item.text} onChange={change.bind(null,index)}/>
                    </li>)
                }
                {
                    options.length < 6  && <li>
                        <span onClick={addOptions}>+</span>
                        添加选项
                    </li>
                }
            </ul>
        </div>
    </div>
}

export default Create